const questionBank = [
  {
    q: '遇到陌生人要求转账怎么办？',
    options: ['立刻转账', '拒绝并报警', '询问对方身份'],
    answer: '拒绝并报警'
  },
  {
    q: '收到中奖短信应如何处理？',
    options: ['点击链接领奖', '忽略删除', '回复个人信息'],
    answer: '忽略删除'
  },
  {
    q: '网络贷款需先交保证金，应该？',
    options: ['交钱', '拒绝', '咨询客服'],
    answer: '拒绝'
  },
  {
    q: '发现可疑诈骗网站，应该？',
    options: ['举报', '浏览', '分享给朋友'],
    answer: '举报'
  },
  {
    q: '电话自称公检法要求汇款，应该？',
    options: ['配合汇款', '挂断电话', '加对方微信'],
    answer: '挂断电话'
  },
  {
    q: '收到陌生链接，应该？',
    options: ['点击查看', '忽略删除', '转发给朋友'],
    answer: '忽略删除'
  },
  {
    q: '遇到网络刷单兼职，应该？',
    options: ['尝试一下', '拒绝参与', '咨询客服'],
    answer: '拒绝参与'
  },
  {
    q: '遇到冒充熟人借钱，应该？',
    options: ['直接转账', '电话核实', '加微信确认'],
    answer: '电话核实'
  },
  {
    q: '遇到冒充银行工作人员，应该？',
    options: ['配合操作', '挂断电话', '提供验证码'],
    answer: '挂断电话'
  },
  {
    q: '遇到网络中奖，应该？',
    options: ['提供个人信息', '忽略信息', '联系客服'],
    answer: '忽略信息'
  }
];

function getRandomQuestions(bank, num) {
  const arr = bank.slice();
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr.slice(0, num);
}

Page({
  data: {
    started: false,
    questions: [],
    answers: {},
    score: 0,
    submitted: false
  },
  onStartQuiz() {
    const questions = getRandomQuestions(questionBank, 5);
    this.setData({
      started: true,
      questions,
      answers: {},
      score: 0,
      submitted: false
    });
  },
  onRadioChange(e) {
    const { name } = e.currentTarget.dataset;
    const { value } = e.detail;
    this.setData({
      [`answers.${name}`]: value
    });
    setTimeout(() => {
      console.log(this.data.answers);
    }, 1000);
  },
  onSubmit(e) {
    const { questions, answers } = this.data;
    if (Object.keys(answers).length !== questions.length) {
      wx.showToast({
        title: '请完成所有题目再提交',
        icon: 'none'
      });
      return;
    }
    let score = 0;
    questions.forEach((q, i) => {
      if (answers[`q${i}`] === q.answer) score+=20;
    });
    this.setData({ score, submitted: true });
    // 存储到本地缓存
    const history = wx.getStorageSync('quizHistory') || [];
    history.push({
      time: new Date().toLocaleString(),
      score,
      total: questions.length * 20
    });
    wx.setStorageSync('quizHistory', history);
    wx.showModal({
      title: '答题结果',
      content: `您的得分：${score} / ${questions.length * 20}`,
      showCancel: false
    });
  },
  onRestartQuiz() {
    this.setData({
      started: false,
      questions: [],
      answers: {},
      score: 0,
      submitted: false
    });
  }
}); 